import style from './index.module.less'
import { Form, TextArea, Button, Toast, Dialog } from 'antd-mobile'
import FilePicker from '@components/filePicker'
import PageComponent from '@components/pageComponent'
import { getCaseDetailRequest, updateData } from './ajax'
import { awaitWrap } from '@src/assets/js/tool'
import { useEffect, useState } from 'react'
import { refreshCaseEditVersion } from '@src/redux/reducers/cases'
import { pop } from '@src/redux/reducers/pages'
import { useAppDispatch } from '@src/redux/hook'
import { requestFiles } from '@src/assets/js/request'
import { setProgress, setProgressVisible } from '@src/redux/reducers/common'

const { Item, useForm } = Form

async function initData (caseid, formRef, setData) {
  Toast.show({ content: '加载中', icon: 'loading', duration: 0 })
  const [e, d] = await awaitWrap(getCaseDetailRequest(caseid))
  if (e === null) {
    Toast.clear()
    if (d) {
      setData(d)
      formRef.setFieldsValue({
        file: (d.claim.file || []).map(li => {
          li.name = li.original_filename
          return li
        })
      })
    }
  }
}

async function submitHandle (caseid, data, d, dispatch) {
  let fileid = ''
  if (d.file && d.file.length > 0) {
    dispatch(setProgressVisible(true))
    const [e, r] = await awaitWrap(requestFiles(d.file, v => { dispatch(setProgress(v)) }))
    dispatch(setProgressVisible(false))
    if (e !== null) {
      return undefined
    }
    if (e === null && r !== null) {
      fileid = r.map(li => li.id).join(',')
    }
  }
  const claim = JSON.parse(JSON.stringify(data.claim))
  const items = claim.items || []
  items.forEach(li => {
    delete li.id
  })
  delete claim.file
  claim.fileid = fileid
  Toast.show({ content: '提交中', icon: 'loading', duration: 0 })
  const [e] = await awaitWrap(updateData(caseid, { claim }))
  if (e === null) {
    Toast.clear()
    Toast.show({ content: '提交成功', icon: 'success' })
    dispatch(refreshCaseEditVersion())
    dispatch(pop())
  }
}

function Main ({ meta: { caseid = '' } = { case: '' } }) {
  const [formRef] = useForm()
  const dispatch = useAppDispatch()
  const [data, setData] = useState(null)
  useEffect(() => {
    if (formRef && caseid) {
      initData(caseid, formRef, setData)
    }
  }, [caseid, formRef])
  return (
    <PageComponent title='编辑仲裁申请书'>
      <Form layout='horizontal' form={formRef} onFinish={d => {
        Dialog.confirm({
          title: '您确定要提交吗？',
          onConfirm: () => {
            submitHandle(caseid, data, d, dispatch)
          }
        })
      }}>
        <Item name='file' label='仲裁申请书'>
          <FilePicker />
        </Item>
        <Item>
          <div className={style.btns}>
            <Button type='submit' color='primary' block>提交</Button>
          </div>
        </Item>
      </Form>
    </PageComponent>
  )
}

export default Main
